package grsu.epam.airline.DAOImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import grsu.epam.airline.DAO.IUserDAO;
import grsu.epam.airline.model.Role;
import grsu.epam.airline.model.UserPrincipal;

public class UserDAOImpl implements IUserDAO {
	private static final String GET_USER_BY_NAME = "select u.user_name, u.password, r.role_id,r.role_type from user u inner join role r on u.role_id=r.role_id where u.user_name=? and u.password=?";
	private Connection conn;

	public UserDAOImpl(Connection conn) {
		this.conn = conn;
	}

	@Override
	public UserPrincipal getUserByName(String userName, String password)
			throws SQLException {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		UserPrincipal user = null;
		try {
			stmt = conn.prepareStatement(GET_USER_BY_NAME);
			stmt.setString(1, userName);
			stmt.setString(2, password);
			rs = stmt.executeQuery();
			while (rs.next()) {
				Role role = new Role(rs.getInt("role_id"),
						rs.getString("role_type"));
				user = new UserPrincipal(rs.getString("user_name"),
						rs.getString("password"), role);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (Exception ignore) {
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (Exception ignore) {
				}
			}
		}
		return user;
	}

	@Override
	public Connection getConnection() {
		return this.conn;
	}
}
